//------------------------------------------------------------------------------
//
// classname: TextLoader
// version: 0.1.0
// author: 小兵( aosnow@yeah.net )
// created: 2013-4-12
// copyright (c) 2013 小兵( aosnow@yeah.net )
// ...
//
//------------------------------------------------------------------------------

package starfire.rpc.loader.elements
{

	import starfire.rpc.loader.LoadMessage;
	import starfire.rpc.loader.LoadState;

	import flash.errors.IOError;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;

	[ExcludeClass]
	public class TextLoader extends LoaderBase
	{
		protected var urlLoader:URLLoader;

		public function TextLoader( message:LoadMessage )
		{
			super( message );
		}

		override protected function executeLoad( message:LoadMessage ):void
		{
			var urlReq:URLRequest = new URLRequest( message.url );

			urlLoader = new URLLoader();
			urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			toggleLoaderListeners( urlLoader, true );

			// 开始加载数据
			try
			{
				updateLoadState( LoadState.LOADING );
				urlLoader.load( urlReq );
			}
			catch( ioError:IOError )
			{
				IOErrorHandler( null, ioError.message );
			}
			catch( securityError:SecurityError )
			{
				securityErrorHandler( null, securityError.message );
			}
		}

		override protected function executeUnload( message:LoadMessage ):void
		{
			updateLoadState( LoadState.UNLOADING );
			urlLoader = null;
			updateLoadState( LoadState.UNINITIALIZED );
		}

		override protected function loadCompleteHandler( event:Event ):void
		{
			toggleLoaderListeners( urlLoader, false );

			var data:String = urlLoader.data;

			// 文件数据保存字节数组
			try
			{
				saveCache( data );
			}
			catch( e:Error )
			{
				return;
			}

			updateLoadState( LoadState.READY );

			// 执行回调函数
			if( complete is Function )
			{
				complete( data );
			}
		}
	}
}
